package com.huixue.cn.ztej.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.support.BindingAwareModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huixue.cn.ztej.bean.ApproveBean;
import com.huixue.cn.ztej.bean.EmployApply;
import com.huixue.cn.ztej.bean.Examine;
import com.huixue.cn.ztej.bean.MechanicalApply;
import com.huixue.cn.ztej.bean.Results;
import com.huixue.cn.ztej.bean.User;
import com.huixue.cn.ztej.constants.UserUtil;
import com.huixue.cn.ztej.enums.RoleStatus;
import com.huixue.cn.ztej.service.SysMechanicaApplyService;
import com.huixue.cn.ztej.service.SysUserService;
import com.huixue.cn.ztej.service.impl.EmployApplyServiceImpl;
import com.huixue.cn.ztej.service.impl.ExamineServiceImpl;
import com.huixue.cn.ztej.utils.annotation.RequestMappingName;
import com.huixue.cn.ztej.weixin.bean.OAuthInfo;
import com.huixue.cn.ztej.weixin.util.WeixinHelper;

/*
 * status = 0 //status 刚申请
 * status = 1 //工段管理员审批
 * status = 2 //项目经理审批
 * status = 3 //部门经理审批
 * status = 4 //工段管理员审批不通过
 * status = 5 //项目经理审批不通过
 * status = 6 //部门经理审批不通过
 */
@Controller
@RequestMapping(value = "/approve")
public class WUserApproveController extends BaseController {

	@Autowired
	SysMechanicaApplyService sysMechanicaApplyService;
	
	@Autowired(required = true)
	SysUserService sysUserService;
	
	@Autowired
	private ExamineServiceImpl examineServiceImpl;
	
	@Autowired
	private EmployApplyServiceImpl employApplyServiceImpl;
	
	@RequestMappingName(value = "审批列表页面")
	@RequestMapping(value = "/list")
	private String listApply(HttpServletRequest request,HttpServletResponse response,Model model){
		OAuthInfo aouAuthInfo  = WeixinHelper.getUserOpenId(request);
		String status = "-1";
		
		
		//根据Openid查找用户
		User currentUser = sysUserService.findUserByOpenId(aouAuthInfo.getOpenId(),false);
		
		if(currentUser!=null){
			request.getSession().setAttribute("currentUser",currentUser);
		}

		if(currentUser==null){
			return "/wx/user/noregister";
		}else if(currentUser.getIsAvailable()==UserUtil.DISABLE_YES){
			model.addAttribute("msg", "账号已禁用,请联系管理员");
			return "/wx/message";
		}
		
		
		//查询机械申请审批
		if(currentUser.getRoleId()!=null && 
				Integer.valueOf(currentUser.getRoleId())>RoleStatus.ROLE_2.getRoleId()){
			Map<String, Object> map = new HashMap<String, Object>();
			/*if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_3.getRoleId()){
				status = "0,3,-3";
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_4.getRoleId()){
				status = "3,4,-4";
				map.put("segmentId", currentUser.getSegmentID());
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId()){
				status = "4,5,-5";
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_6.getRoleId()){
				status = "5,6,-6";
			}*/
			
			if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_4.getRoleId()){
				map.put("segmentId", currentUser.getSegmentID());
				status = "0,4,-4";
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_3.getRoleId()){
				status = "4,3,-3";
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId()){
				status = "3,5,-5";
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_6.getRoleId()){
				status = "5,6,-6";
			}
			
			map.put("proId", currentUser.getProjectID());
			map.put("state", status);
			//查询机械申请审批
			Results mechanResult = sysMechanicaApplyService.listMechanicaApply(map);
			model.addAttribute("mechanResult", mechanResult);
			
			int []stateIds = new int []{-1};
			Map<String, Object> emap = new HashMap<String, Object>();
			//查找用工申请
			if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_4.getRoleId()){
				stateIds = new int[]{0,4,-4};
				emap.put("segmentId", currentUser.getSegmentID()+"");
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId()){
				stateIds = new int[]{4,5,-5};
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_6.getRoleId()){
				stateIds = new int[]{5,6,-6};
			}
			System.out.println("===角色=currentUser.getSegmentID====="+emap.get("segmentId"));
			emap.put("proId", currentUser.getProjectID());
			emap.put("state", stateIds);
			Results empoyResults = employApplyServiceImpl.searchByPage(emap,0,200);
			model.addAttribute("empoyResults", empoyResults);
			
			model.addAttribute("currentUser", currentUser);
		}else{
			return "/wx/approve/noapprove";
		}
		return "/wx/approve/list";
	}
	
	@RequestMapping(value = "/todo",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody
	private Results approve(@RequestBody ApproveBean apply,HttpServletRequest request,HttpServletResponse response,Model model){
		//查找申请
		
		if(apply.getApplyType()==1){
			User currentUser = (User)(request.getSession().getAttribute("currentUser"));
			
			EmployApply employApply = employApplyServiceImpl.findApplyById(apply.getApplyId());
			
			if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId() && apply.getStatus()<0){
				employApply.setIsPlan(0);
			}
			
			if((Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId())){
				float  fee = employApply.getOnstructionHour().floatValue()*apply.getPrice();
				employApply.setHourPrice(new BigDecimal(apply.getPrice()));
				employApply.setFee(new BigDecimal(fee));
			}
			employApply.setState(apply.getStatus());
			employApplyServiceImpl.updateById(employApply);
			
			//添加审批过程
			Examine examine = new Examine();
			examine.setApplyId(apply.getApplyId());
			examine.setExamineId(apply.getApproveUserId());
			examine.setExamineName(apply.getApproveUserName());
			examine.setExamineRoleId(Integer.valueOf(currentUser.getRoleId()));
			//大于0 同意 小于0 不同意
			examine.setState(apply.getStatus()>0?1:2);
			examine.setType(apply.getApplyType());
			examine.setExamineRemark(apply.getApproveRemark());
			if(apply.getStatus()>0){
				if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_4.getRoleId()){
					examine.setContent("工段管理审核通过");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId()){
					examine.setContent("合同部审核通过");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_6.getRoleId()){
					examine.setContent("项目部审核通过");
				}
				examine.setState(1);
			}else{
				if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_4.getRoleId()){
					examine.setContent("工段退回");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId()){
					examine.setContent("合同部取消");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_6.getRoleId()){
					examine.setContent("项目部退回");
				}
				examine.setState(2);
			}
			
			examine.setExamineTime(new Date());
			examineServiceImpl.add(examine);
			
			Results results = new Results("0", "审批成功", "/approve/success");
			return results;
		}else if(apply.getApplyType()==2){
			User currentUser = null;
			currentUser = (User)(request.getSession().getAttribute("user"));
			if(currentUser == null){
				currentUser = (User)(request.getSession().getAttribute("currentUser"));
			}
			
			MechanicalApply mechanical = sysMechanicaApplyService.findById(apply.getApplyId());
			mechanical.setState(apply.getStatus());
			if((Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId())){
				if(mechanical.getDeductHour()==null){
					mechanical.setDeductHour(0.0f);
				}
				/*float  fee = (mechanical.getUseHours() - mechanical.getDeductHour())
						*mechanical.getQuantity()
						*apply.getPrice();*/
				float  fee = (mechanical.getUseHours())
						*mechanical.getQuantity()
						*apply.getPrice();
				mechanical.setPrice(apply.getPrice());
				mechanical.setFee(fee);
				
			}
			sysMechanicaApplyService.update(mechanical);
			
			
			//添加审批过程
			Examine examine = new Examine();
			examine.setApplyId(apply.getApplyId());
			examine.setExamineId(apply.getApproveUserId());
			examine.setExamineName(apply.getApproveUserName());
			examine.setExamineRoleId(Integer.valueOf(currentUser.getRoleId()));
			//大于0 同意 小于0 不同意
			examine.setState(apply.getStatus()>0?1:2);
			examine.setType(apply.getApplyType());
			examine.setExamineRemark(apply.getApproveRemark());
			//examine.setContent(apply.getStatus()>0?"同意":"不同意");
			if(apply.getStatus()>0){
				if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_3.getRoleId()){
					examine.setContent("物资部审核通过");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_4.getRoleId()){
					examine.setContent("工段管理审核通过");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId()){
					examine.setContent("合同部审核通过");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_6.getRoleId()){
					examine.setContent("项目部审核通过");
				}
				examine.setState(1);
			}else{
				if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_3.getRoleId()){
					examine.setContent("物资部退回");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_4.getRoleId()){
					examine.setContent("工段退回");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId()){
					examine.setContent("合同部取消");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_6.getRoleId()){
					examine.setContent("项目部退回");
				}
				examine.setState(2);
			}
			examine.setExamineTime(new Date());
			examineServiceImpl.add(examine);
			
			
			Results results = new Results("0", "审批成功", "/approve/success");
			
			return results;
		}
		
		return null;
	}
	
	/**
	 * 审批成功
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/success")
	private String success(HttpServletRequest request,HttpServletResponse response,Model model){
		model.addAttribute("msg", "审批成功");
		return "/wx/message";
	}
	
	@RequestMappingName(value = "我的申请列表")
	@RequestMapping(value = "/myApply")
	private String myApply(HttpServletRequest request,HttpServletResponse response,Model model){
		OAuthInfo aouAuthInfo  = WeixinHelper.getUserOpenId(request);
		
		String status = "-1";
		Map<String, Object> map = new HashMap<String, Object>();
		
		//根据Openid查找用户
		User currentUser = null;
		
		currentUser = sysUserService.findUserByOpenId(aouAuthInfo.getOpenId(),false);
		if(currentUser!=null){
			//request.getSession().setAttribute("currentUser",currentUser);
		}

		if(currentUser==null){
			return "/wx/user/noregister";
		}else if(currentUser.getIsAvailable()==UserUtil.DISABLE_YES){
			model.addAttribute("msg", "账号已禁用,请联系管理员");
			return "/wx/message";
		}
		
		if(currentUser.getRoleId()!=null && 
				Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_2.getRoleId()){
			
			//机械申请
			Results mechanResult = sysMechanicaApplyService.listMechanicalApplyByUserId(currentUser.getUser_id());
			model.addAttribute("mechanResult", mechanResult);
			model.addAttribute("user", currentUser);
			
			//用工申请
			Results empoyResults = employApplyServiceImpl.listEmployApplyByUserId(currentUser.getUser_id());
			model.addAttribute("empoyResults", empoyResults);
			
		}else{
			model.addAttribute("msg", "没有申请权限");
			return "/wx/message";
		}
		return "/wx/apply/list";
	}
	
}
